$(document).bind('mobileinit',function(){
});

var dj = dj || {};

dj.params_default = {
    price_at_most : null,
    price_at_least : null,
    value_at_most : null,
    value_at_least : null,
    discount_at_most : null,
    discount_at_least : null,
    categories : [],
    providers : [],
    national : 'false',
    keywords : null,
    keywords_not : null,
    //location : 'New York',
    radius : 20,
    shortcuts : 'daily-deals',
    order : 'expires_at',
    per_page : 10
};

dj.main = {
    
    page : 1,
    total : 0,
    
    retry : 0,
    
    items : {},
    
    init : function()
    {
        var params = {};
        
        var stored = localStorage.getItem('params');

        dj.params = stored ? $.parseJSON(stored) : dj.params_default;
        
        var location = dj.geo.get();
        $('a.link-city').text(location.city);

        this.fetchDeals();

        $('#form-search').bind('submit', function(e) {
          dj.main.page = 1;
          params.query = $('#search-query').val()
          dj.main.fetchDeals(params, true);

          return false;
        });

        $('#link-more').bind('click', function() {
          dj.main.page++;
          params.query = $('#search-query').val()
          dj.main.fetchDeals(params);
          return false;
        });

    },
    
    fetchDeals : function(params, clear)
    {
        var params = params || {};
        
        if (clear) $('#deals-list').empty();
        
        $.mobile.showPageLoadingMsg();
        
        var url = 'http://api.sqoot.com/v1/offers';
        
        $.each(dj.params, function(key, value) {
            if (value != null) params[key] = value;
        });

        params.affiliate_token = 'q577ig';
        params.page = this.page;
        
        var location = dj.geo.get();
        params.location = location.lat + ',' + location.lng;
                
        //console.log(params);
        
        $.ajax({
          url: url,
          data: params,
          success: function(data) {
            dj.main.buildList(data);
            $.mobile.hidePageLoadingMsg();
        },
          error : function(data) {
            
            if (dj.main.retry < 3) {
                
                dj.main.fetchDeals(params);
                dj.main.retry++;
            } else {
                dj.main.retry = 0;
            }
            
            $.mobile.hidePageLoadingMsg();
          },
          dataType: 'json'
        });
    },
    
    buildList : function(deals, callback) {
    
      dj.main.total = deals.total;

      var deals_list = '';
      
      var subtitle, title, expire = '';

      $.each(deals.offers, function(key, val) {

        dj.main.items[val.offer.id] = val.offer;

        title = val.offer.title;
        
        expire = val.offer.expires_at_in_words ? ' - expires in <b>' + val.offer.expires_at_in_words + '</b>' : ''; 
          
        subtitle = val.offer.short_title ? val.offer.short_title : 'Save ' + val.offer.discount + '% Original Price ' + val.offer.value + '$';
          
        deals_list += '<li><a class="link" rel="' + val.offer.id + '" title="' + title + '">'
        + '<img src="http://images.sqoot.com/' + val.offer.id + '/100x100C?affiliate_token=q577ig" title="' + title + '" />'
        + '<h5>' + title + '</h5><span class="ui-li-count">' + val.offer.price + ' $</span>'
        + '<p><b>' + subtitle + '</b>'
        + '<br>from <b>' + val.offer.source + '</b>' + expire + '</p>'
        +'</a></li>';
      });
      
      $('#deals-list').append(deals_list).listview('refresh');
      
      var left = (deals.total - (deals.per_page * deals.page));
      
      if (left <= 0) {
          $('#link-more').hide();
      } else {
          $('#link-more').show();
          $('#count-total').html(left);
      }

      if (typeof callback == 'function') callback();
      
      $('a.link').click(function(e) {
          dj.main.showPreview(this.rel);
      });

    },
    
    showPreview : function(id)
    {
        var url = 'http://click.sqoot.com/' + id + '/q577ig?ref=crm';
        
        var deal = this.items[id];

        $('#preview-description').empty().html(deal.description);
        $('#preview-title').empty().html('<a href="' + url + '" class="deal-tab">' + deal.title + '</a>');

        var img = '<a href="' + url + '" class="deal-tab"><img src="http://images.sqoot.com/' + id + '/200x200C?affiliate_token=q577ig" class="preview" width="200" height="200" /></a>';

        $('#preview-img').empty().html(img);

        $.mobile.changePage('#preview');

        if (!dj.util.empty(deal.locations[0].latitude)) {
            
            dj.main.showLocation(deal.locations[0].latitude, deal.locations[0].longitude);
        }
        
        $('#preview-price').html(deal.price);
        $('#preview-off').html(deal.discount);
        
        if (!dj.util.empty(deal.expires_at_in_words)) {
            $('#preview-expire').empty().html('<h3>Expires in ' + deal.expires_at_in_words + '</h3>');
        }
        
        $('a.deal-tab').unbind().bind('click', function() {
          window.open(url);
        });
    },
    
     showLocation : function(lat, lng)
     {
        var latlng = new google.maps.LatLng(lat, lng);
        var myOptions = {
          zoom: 15,
          center: latlng,
          navigationControl: true,
          mapTypeControl: false,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var canvas = document.getElementById("preview-map");

        var map = new google.maps.Map(canvas, myOptions);

        var marker = new google.maps.Marker({
                  position: latlng,
                  map: map,
                  icon : 'img/price-tag.png'
        });
    }

};

dj.settings = {
    
    init : function() {

        dj.settings.bindings();
        
        dj.settings.prefill();
    },
    
    bindings : function() {
        
        $('a.settings-save').bind('click', function() {
            
            dj.settings.onSave();
        });
        
        $('#link-reset').bind('click', function() {
            dj.params = dj.params_default;
            localStorage.removeItem('params');
            $('#deals-list').empty();

            $.mobile.changePage('#main');
            
            dj.main.fetchDeals();
        });
        
        $('a.btn-close').bind('click', function() {
            $.mobile.changePage('#settings');
        });
    },
    
    onSave : function() {
        
        if ($('#field-price-max').val() > 0) {
            dj.params.price_at_most = $('#field-price-max').val();
        }

        if ($('#field-discount-min').val() > 0) {
            dj.params.discount_at_least = $('#field-discount-min').val();
        }

        if ($('#field-radius').val() > 0) {
            dj.params.radius = $('#field-radius').val();
        }

        if ($('#field-national').val() == 'true') {
            delete dj.params.national;
        } else {
            dj.params.national = 'false';
        };

        dj.params.categories = $('#field-categories').val();
        dj.params.providers = $('#field-providers').val();

        var shortcuts = new Array();
        $('#field-shortcuts :checked').each(function() {
               shortcuts.push($(this).val());
        });

        dj.params.shortcuts = shortcuts.join(',');

        console.log(dj.params);

        localStorage.setItem('params', JSON.stringify(dj.params));;

        $.mobile.changePage('#main');

        dj.main.fetchDeals({}, true);
    },
    
    prefill : function() {
                
        $('#field-price-max').val(dj.params.price_at_most);
        $('#field-discount-min').val(dj.params.discount_at_least);
        $('#field-radius').val(dj.params.radius);
        
        $('input.slider').slider();
        
        //console.log(dj.params.national);
        
        if (typeof dj.params.national == "undefined") {
            $('#field-national option[value="true"]').attr('selected', 'selected');
            
            $('select.switch').slider('refresh');
        }
        
        if (!dj.util.empty(dj.params.providers)) {
            $.each(dj.params.providers, function(key, value) {

                $('#field-providers option[value="' + value + '"]').attr('selected', 'selected');
            });
        }
        
        if (!dj.util.empty(dj.params.categories)) {
            $.each(dj.params.categories, function(key, value) {

                $('#field-categories option[value="' + value + '"]').attr('selected', 'selected');
            });
        }
        
        $('select.multi').selectmenu('refresh');
        
        if (!dj.util.empty(dj.params.shortcuts)) {
            
            var shortcuts = dj.params.shortcuts.split(',');
            
            $.each(shortcuts, function(key, value) {

                var radio = $('#field-shortcuts input[value="' + value + '"]').attr('checked', 'checked');

                radio.checkboxradio("refresh");
            });
            
        }
    }
};

dj.geo = {
    
    map : null,
    marker : null,
    
    locality : {
        city : 'New York',
        land : 'US',
        lat : 40.7143528,
        lng : -74.0059731
    },
    
    temp : {},
    
    init : function() {
        
        dj.geo.detect();
        
        $('#link-clear').bind('click', function() {
            localStorage.removeItem('location');
            dj.geo.detect();
        });
        
        $('#form-location').bind('submit', function() {
            dj.geo.geocode($('#field-location').val());
            return false;
        });
    },
    
    get : function() {
        
        // stored ?
        var data = localStorage.getItem('location');
        
        if (data) {
            dj.geo.locality = $.parseJSON(data);
        }
        
        return dj.geo.locality;
    },
    
    save : function()
    {
        localStorage.setItem('location', JSON.stringify(dj.geo.locality));
        $('a.link-city').text(dj.geo.locality.city);
 
        $.mobile.changePage('#main');
        dj.main.fetchDeals({}, true);
    },
    
    detect : function() {
        
        var data = localStorage.getItem('location');
        
        if (data) {
            var loc = $.parseJSON(data);
            dj.geo.showLocation('map', loc);
            return;
        }
        
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(dj.geo.success, dj.geo.error);
        } else {
          dj.geo.showLocation('map', dj.geo.locality);
        }
    },
    
    success : function(loc) {

        var data = {
            'lat'  : loc.coords.latitude,
            'lng'  : loc.coords.longitude
        };
        
        dj.geo.showLocation('map', data);
    },
    
    showLocation : function(div, loc) {
        
        var latlng = new google.maps.LatLng(loc.lat,  loc.lng);

        dj.geo._showLocation(div, latlng);
    },
    
    _showLocation : function(div, latlng) {
        
        var myOptions = {
          zoom: 5,
          center: latlng,
          navigationControl: true,
          mapTypeControl: false,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var canvas = document.getElementById(div);

        dj.geo.map = new google.maps.Map(canvas, myOptions);

        dj.geo.marker = new google.maps.Marker({
          position : latlng,
          map : dj.geo.map,
          draggable : true,
          icon : 'img/home-icon.png'
        });
        
        dj.geo.reocode(latlng);
        
        google.maps.event.addListener(dj.geo.marker, 'dragend', function(e){
            
            if (!dj.util.empty(dj.geo.infowindow)) {
                dj.geo.infowindow.close();
            }
            
            dj.geo.reocode(e.latLng);
        });
    },
    
    reocode : function(latlng) {
        
        var geocoder = new google.maps.Geocoder();
        
        geocoder.geocode({'latLng': latlng}, function(results, status) {
            
            if (status == google.maps.GeocoderStatus.OK) {

                var loc = results[0];
                
                $.each(results[0].address_components, function(key, value) {
                    if (value.types[0] === 'locality') {
                        dj.geo.temp.city = value['long_name'];
                    } else if (value.types[0] === 'country') {
                        dj.geo.temp.land = value['short_name'];
                    }

                });
                
                if (dj.geo.temp.land === 'US') {
                    dj.geo.locality.city = dj.geo.temp.city;
                    dj.geo.locality.land = dj.geo.temp.land;
                    dj.geo.locality.lat = loc.geometry.location.lat();
                    dj.geo.locality.lng = loc.geometry.location.lng();
                } else {
                    dj.geo.showLocation('map', dj.geo.locality);
                    return;
                }
                
                latlng = loc.geometry.location;

                if (results[1]) {

                    //dj.geo.map.setZoom(11);
                    dj.geo.map.setCenter(latlng);

                    dj.geo.infowindow = new google.maps.InfoWindow({
                        content: dj.geo.locality.city + ', ' + dj.geo.locality.land
                                 + '<p><button onclick="dj.geo.save();" id="btn-location-save">Save Location</button></p>'
                    });

                    dj.geo.infowindow.open(dj.geo.map, dj.geo.marker);
                }

            } else {
                //console.log("Geocoder failed due to: " + status);
                dj.geo.showLocation('map', dj.geo.locality);
            }
      });

    },
    
    geocode : function(address) {

      var geocoder = new google.maps.Geocoder();
        
      dj.geo.marker.setMap(null);

      geocoder.geocode( {'address': address}, function(results, status) {
          
        if (status == google.maps.GeocoderStatus.OK) {
          dj.geo._showLocation('map', results[0].geometry.location);
        } else {
          console.log("Geocode was not successful for the following reason: " + status);
        }
      });

    },
    
    error : function(msg) {
        
        msg = msg || 'error';
        
        console.log(msg);
    }
    
};

dj.util = {
    empty : function(obj) {
        return (typeof obj == "undefined") || obj === "" || obj === false || obj === null;
    }
};